<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="委外加工单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入委外加工单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="委外加工商" name="processor" required>
						<uni-data-select mode="underline" placeholder="请选择委外加工单号" v-model="form.processor" :localdata="client_list"
							:clear="true" :disabled="pageInfo.type == 'edit'" />
					</uni-forms-item>
					<uni-forms-item label="下单日期" name="order_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择下单日期" :clear-icon="false" v-model="form.order_date"
								@show="car_popup_Show = false" @maskClick="car_popup_Show = true" @change="car_popup_Show = true"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="交货日期" name="delivery_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择交货日期" :clear-icon="false"
								v-model="form.delivery_date" @show="car_popup_Show = false" @maskClick="car_popup_Show = true"
								@change="car_popup_Show = true" :border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
			</view>

			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" :animation="cartShakeAnim" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${form.product_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(form.product_list.length) }" v-show="car_popupShow"
					@click.stop="save">提交</view>
				<view style="margin-left: auto;" v-show="!car_popupShow"><u--text text="点击查看" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>

			<custom-popup :popupShow="car_popupShow" mode="bottom" title="产品" class="car-popup-custom"
				@close="car_popupShow = false" height="70vh">
				<z-paging ref="paging_car" v-if="car_popupShow" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.product_list" @query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="btn-box">
								<view>
									<u-button type="primary" size="small" text="选择产品" @click="popupShow = true"></u-button>
								</view>
							</view>
						</view>
					</template>
					<uni-card v-for="(item, index) in form.product_list" :key="index" margin="5px" spacing="0">
						<template v-slot:title>
							<uni-list>
								<uni-list-item :title="item.name" :note="item.code" thumbSize="lg">
									<template v-slot:footer>
										<up-icon name="trash" color="red" size="28" @click="removeTransfer(index)"/>
									</template>
								</uni-list-item>
							</uni-list>
						</template>
						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con" style="align-items: normal;">
							<view class="ctent" style="flex: none;">仓库【库存】：</view>
							<view class="ctent">{{ item.inventory_info }}</view>
						</view>
						<view class="ctent flex1" style="color:blue;text-decoration: underline;" @click="bomAct(item)">BOM数量：{{
							item.bom_num }}
						</view>
						<view class="ctent flex1">基本单位销售价(元)：{{ item.unit_main_price }}</view>
						<view class="con">
							<view class="ctent" style="flex: none;">加工数量：</view>
							<custom-num-box v-model="item.num" :min="0" @change="changeNum($event, item)"
								:asyncChange="true"></custom-num-box>
						</view>
						<view class="ctent flex1">发料数量：{{ item.f_num }}</view>
						<view class="con">
							<view class="ctent" style="flex: none;">加工单价(元)：</view>
							<custom-num-box v-model="item.machining_price" :min="0"></custom-num-box>
						</view>
					</uni-card>
					<template #bottom>
						<view class="zhanwei"></view>
					</template>
				</z-paging>
				<custom-popup :popupShow="popupShow" mode="center" :title="'选择产品'" width="96%" height="60%" class="popup-custom"
					@close="popupShow = false" :closeOnClickOverlay="false">
					<FlyBall ref="flyBall" />
					<z-paging v-if="popupShow" ref="paging" :fixed="false" v-model="dataList" @query="queryList">
						<template #top>
							<view class="zpagin_top">
								<view class="search">
									<custom-search v-model="searchVal" @search="refreshList" placeholder="请输入产品名称或编号" />
								</view>
							</view>
						</template>
						<uni-card v-for="(item, index) in dataList" :key="item.id" margin="5px" spacing="0">
							<template v-slot:title>
								<uni-list>
									<uni-list-item :title="item.name" :note="item.code" thumbSize="lg">
										<template v-slot:footer>
											<view :id="`goods-btn${index}`">
												<u-button type="primary" size="small" shape="circle" text="添加" @click="hanldAddWar(index, item)"
													:disabled="isInTransfer(item.id)"></u-button>
											</view>
										</template>
									</uni-list-item>
								</uni-list>
							</template>
							<view class="ctent">规格：{{ item.specification }}</view>
							<view class="ctent">成本：{{ item.all_cost }}</view>
						</uni-card>
					</z-paging>
				</custom-popup>
				<custom-popup :popupShow="bom_popupShow" mode="center" :title="proName + '的【BOM】'" width="96%" height="60%"
					class="popup-custom" @close="bom_popupShow = false" :closeOnClickOverlay="false">
					<z-paging ref="paging" :fixed="false" :refresher-enabled="false" :loading-more-enabled="false">
						<uni-card v-for="(item, index) in bom_dataList" :title="item.name" :key="index" margin="5px" spacing="0">
							<view class="con">
								<view class="ctent">用量：{{ item.num }}</view>
								<view class="ctent">损耗率：{{ item.loss }}%</view>
							</view>
							<view class="ctent">采购价(元)：{{ item.default_supplier_price }}</view>
						</uni-card>
					</z-paging>
				</custom-popup>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import enOrderApi from '../../../api/entrust/en_order'
import { generateCode, shakeCartIcon, getRectDom } from '@/utils/index.js';
import FlyBall from '@/components/flyBall'
//页面标题
const pageInfo = reactive({
	navbarTitle: '委外加工单',
	type: '',
	edit_id: null,
});
onLoad(option => {
	get_supplier_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(修改)'
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(新增)'
		form.code = generateCode('WT')
	}
})
//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('WT')
	}
}

const refForm = ref(null);
const form = reactive({
	code: '',
	processor: null,
	delivery_date: '',
	order_date: '',
	desc: '',
	product_list: []
})
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请填写委外加工单号' }] },
	order_date: { rules: [{ required: true, errorMessage: '请填写下单日期' }] },
	delivery_date: { rules: [{ required: true, errorMessage: '请填写交货日期' }] },
	processor: { rules: [{ required: true, errorMessage: '请选择委外加工商' }] },
}

function get_detail(id) {
	enOrderApi.machining_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		form.product_list = res.machining_products.map(v => {
			const bom_list = JSON.parse(v.product.bom_info)
			const bom_num = bom_list.bom_info.reduce((total, item) => {
				return total + (Number(item.num) || 0)
			}, 0)
			return {
				id: v.product.id,
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				bom_num: bom_num,
				bom_info: v.product.bom_info,
				unit_main_price: v.product.unit_main_price,
				num: v.num,
				f_num: bom_num * v.num,
				machining_price: v.machining_price,
				craft: v.craft,
				inventory_info: v.product.stock_info.map(v => (`${v.warehouse_name}【${v.unit_info}】`)).join('、'),
			}
		})
	})
}

const paging = ref(null);
const searchVal = ref('')
const dataList = ref([])
function queryList(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		if_open: '1',
		search: searchVal.value
	}
	enOrderApi.get_product(params).then((res) => {
		paging.value.complete(res.results);
	})
}

function refreshList() {
	paging.value.reload();
}

const proName = ref('')
const bom_dataList = ref([])
const bom_popupShow = ref(false)
function bomAct(item) {
	proName.value = item.name
	bom_dataList.value = JSON.parse(item.bom_info).bom_info
	bom_popupShow.value = true
}

function changeNum(e, row) {
	row.num = e.value
	row.f_num = Number((row.num * row.bom_num).toFixed(2))
}

//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			enOrderApi.post_machining(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			enOrderApi.patch_machining(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}

const client_list = ref([])
function get_supplier_list() {
	const params = { page: 1, page_size: 99999, classify: '2' }
	enOrderApi.get_supplier(params).then(res => {
		client_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
}

const popupShow = ref(false);
const car_popupShow = ref(false);
const car_popup_Show = ref(true);
const paging_car = ref(null);
function queryList_car() {
	paging_car.value.complete(form.product_list);
}
function isInTransfer(id) {
	return form.product_list.some(item => item.id === id)
}
function removeTransfer(index) {
	form.product_list.splice(index, 1)
	paging_car.value.complete(form.product_list);
}
const cartShakeAnim = ref()
const flyBall = ref({});
const { proxy } = getCurrentInstance()
async function hanldAddWar(index, item) {
	const dataIndex = `#goods-btn${index}`
	const startRect = await getRectDom(dataIndex, proxy);
	const endRect = await getRectDom('.cartIcon', proxy);
	//小球动画完成回调函数
	const bom_list = JSON.parse(item.bom_info)
	flyBall.value.launch(startRect, endRect, () => {
		if (isInTransfer(item.id)) return;
		form.product_list.push({
			...item,
			bom_num: bom_list.bom_info.reduce((total, item) => {
				return total + (Number(item.num) || 0)
			}, 0),
			inventory_info: item.stock_info.map(v => (`${v.warehouse_name}【${v.unit_info}】`)).join('、'),
			num: 0
		})
		cartShakeAnim.value = shakeCartIcon()
	})
}
//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('en_order:refresh')
		}
	})
}
</script>

<style lang="scss" scoped></style>